<template>
  <div class="my-container d-flex flex-column p-3">
    <div class="shadow rounded-lg d-flex flex-column">
      <div class="p-3">
        <div class="d-flex flex-row flex-wrap ">
          <div class="col-1 col-center">
            <el-button type="success" @click="returnUrl()">返回</el-button>
          </div>
          <div class="col-13 col-center">
            <span class="font-weight-bold">设备名称：</span>
            <span>{{ row.deviceName }}</span>
          </div>
          <div class="col-13 col-center">
            <span class="font-weight-bold">设备编码：</span>
            <span>{{ row.deviceCode }}</span>
          </div>
          <div class="col-13 col-center">
            <span class="font-weight-bold">设备位置：</span>
            <span>{{ row.deviceOfRegionSysName }}</span>
          </div>
          <div class="col-13 col-center">
            <span class="font-weight-bold">创建时间：</span>
            <span>{{ row.createTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="col shadow rounded-lg mt-3 d-flex flex-column">
      <div class="p-3 d-flex flex-column col" style="position: relative;">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="设备实时数据信息" name="1" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="设备数据看板信息" name="2"></el-tab-pane>
          <el-tab-pane label="设备控制记录" name="6" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="设备参数修改记录" name="7" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="设备告警信息" name="3" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="设备故障信息" name="4" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="设备脱扣信息" name="5" v-if="type == 'deviceQuery'"></el-tab-pane>
          <el-tab-pane label="版本升级记录" name="8" v-if="type == 'deviceQuery'"></el-tab-pane>
        </el-tabs>

        <div class="tab-buttom" v-if="activeName == '1' || activeName == '2'">
          <!--          <el-button size="small" type="primary" @click="hanldeMake('open')">合闸</el-button>-->
          <!--          <el-button size="small" type="primary" @click="hanldeMake('close')">分闸</el-button>-->
          <el-button v-if="btnInfo.isControlShow=='show'" size="small" type="primary" @click="handlerOpenControl()">
            指令控制
          </el-button>
          <el-button v-if="btnInfo.isChangeShow=='show'" size="small" type="primary" @click="handlerParams()">参数修改
          </el-button>
        </div>
        <div class="tab-buttom" v-if="activeName == '8'">
          <el-button size="small" type="primary" @click="handlerFirmware()">固件直发</el-button>
        </div>

        <ModelInfo :deviceCode="row.deviceCode" v-if="activeName == '1'"></ModelInfo>

        <DataBoard :deviceCode="row.deviceCode" v-if="activeName == '2'"></DataBoard>

        <deviceControlInfo :deviceCode="row.deviceCode" v-if="activeName == '6'"></deviceControlInfo>

        <editParamsData :deviceCode="row.deviceCode" v-if="activeName == '7'"></editParamsData>

        <WarnInfo :deviceCode="row.deviceCode" v-if="activeName == '3'"></WarnInfo>

        <FaultInfo :deviceCode="row.deviceCode" v-if="activeName == '4'"></FaultInfo>

        <faultDetailInfo :deviceCode="row.deviceCode" v-if="activeName == '5'"></faultDetailInfo>

        <deviceVersionInfo :deviceCode="row.deviceCode" v-if="activeName == '8'"></deviceVersionInfo>
      </div>
    </div>

    <!-- 弹框 -->
    <yc-dialog ref="ycSmsDialog" dialogTitle="短信验证码" dialogWidth="30%" :showCenter="false">
      <template #content>
        <el-row class="d-flex justify-content-center" v-loading="loading">
          <el-col :span="16">
            <el-input v-model="yzm" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="8" class="d-flex align-items-center justify-content-center">
            <el-button type="primary" :disabled="disabled" @click="getCode()">{{title}}</el-button>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="selectParamsSave">发送</el-button>
        <el-button @click="$refs.ycSmsDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 指令控制 -->
    <yc-dialog ref="controlDialog" dialogTitle="指令控制" :showCenter="false">
      <template #content>
        <div class="w-100 h-100" v-loading="loading">
          <div class="mb-3" v-for="(item,index) in controlDataList" :key="index">
            <div class="mb-3 font-16 font-weight-bold ml-1">{{item.name}}</div>
            <div class="d-flex flex-wrap">
              <div class="mr-2 ml-1 mb-3" v-for="(itemY,indexY) in item.list" :key="indexY" @click="editControl(itemY)">
                <el-button size="small" plain type="primary">{{itemY.commandName}}</el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="$refs.controlDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 参数修改 -->
    <yc-dialog ref="paramsDialog" dialogTitle="参数修改" :showCenter="false">
      <template #content>
        <el-table
          :data="paramsTableData"
          border
          style="width: 100%"
          class="elTable"
          ref="tableRef"
        >
          <el-table-column type="index" label="序号" width="60" align="center"/>
          <el-table-column prop="parameterName" label="参数名称" align="center"/>
          <el-table-column prop="parameterCode" label="参数代码" align="center"/>
          <el-table-column prop="parameterValue" label="参数值" align="center"/>
          <el-table-column prop="parameterValueName" label="参数值名称" align="center"/>
          <el-table-column label="修改值" align="center" width="200">
            <template slot-scope="{row}">
              <el-select v-if="row.itemList" v-model="row.parameterValue">
                <el-option
                  v-for="item in row.itemList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
              <el-input v-else v-model="row.parameterValue"/>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="editParamsSave">保存</el-button>
        <el-button @click="$refs.paramsDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 固件直发 -->
    <yc-dialog ref="firmwareDialog" dialogTitle="固件直发" :showCenter="false">
      <template #content>
        <el-form ref="firmwareFormRef" :rules="firmwareRules" :model="newFirmwareModel" label-width="100px">
          <el-form-item label="固件版本号" prop="version">
            <el-input v-model="newFirmwareModel.version"/>
          </el-form-item>
          <el-form-item label="上传固件" prop="fileUrl">
            <el-upload
              :headers="headers"
              class="avatar-uploader"
              :before-upload="beforeUpload"
              :action="$uploadUrl + upload"
              :show-file-list="false"
              :on-success="handleLicenseSuccess"
              v-model="newFirmwareModel.fileUrl"
            >
              <img v-if="newFirmwareModel.fileUrl" :src="newFirmwareModel.fileUrl" class="imgCla"
                   style="display: inline-block; width: 100px; height: 100px; vertical-align: middle"/>
              <i v-else class="el-icon-plus avatar-uploader-icon" style="width: 100px; height: 100px;"></i>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="editFirmwareSave">保存</el-button>
        <el-button @click="$refs.firmwareDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>
  </div>
</template>

<script>
  import DataBoard from "./components/dataBoard.vue"
  import faultDetailInfo from "./components/faultDetailInfo.vue"
  import FaultInfo from "./components/faultInfo.vue"
  import deviceControlInfo from "./components/deviceControlInfo.vue"
  import editParamsData from "./components/editParamsData.vue"
  import ModelInfo from "./components/modelInfo.vue"
  import WarnInfo from "./components/warnInfo.vue"
  import deviceVersionInfo from "./components/deviceVersionInfo.vue"
  import ycDialog from "@/components/pageDialog"
  import {
    makeDeviceOpOrClose,
    queryIsShowButton,
    getSmsCode,
    makeDeviceOpOrCloseSms,
    queryParamCanUpdateList,
    saveParamCanUpdate,
    queryControlList,
    makeDeviceControl,
    makeDeviceControlSms,
    insertInitFirmware
  } from "@/api/showManage/index"
  import { getToken } from "@/utils/auth"

  export default {
    components: {
      ycDialog,
      DataBoard,
      faultDetailInfo,
      FaultInfo,
      deviceControlInfo,
      ModelInfo,
      WarnInfo,
      editParamsData,
      deviceVersionInfo
    },
    data() {
      return {
        row: {},
        activeName: this.$route.query.type == "deviceQuery" ? "1" : "2",
        type: this.$route.query.type,
        btnInfo: {},
        disabled: false, //是否禁用按钮
        timer: null, //计时器
        second: "", //倒计时
        // smsData: "",
        yzmType: "",
        yzmCode: "",
        yzm: "",
        loading: false,
        paramsTableData: [],
        paramsTableData2: [],
        controlDataList: [],
        controlObj: {},
        addOrUpdateLoading: false,

        newFirmwareModel: {
          version: "",
          fileUrl: ""
        },
        firmwareRules: {
          version: [{ required: true, message: "请输入固件版本号", trigger: "blur" }],
          fileUrl: [{ required: true, message: "请上传固件包", trigger: "blur" }]
        },
        fileUrl: "",
        headers: {
          token: getToken()
        },
        upload: "/uploadManager/upload" //上次图片接口路径
      }
    },
    computed: {
      title() {
        return this.disabled ? `重新获取（${this.second}）` : "获取验证码"
      }
    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() {
      this.row = this.$route.query
    },
    // 生命周期 - 挂载完成（访问DOM元素）
    mounted() {
      this.queryIsShowButton()
    },
    // 存放方法事件 - 会在数据变化时被调用
    methods: {
      returnUrl() {
        // this.$router.go(-1)
        this.$router.push({
          path: "/showManage/deviceQuery",
          query: {
            pageIndex: this.row.pageIndex,
            pageSize: this.row.pageSize,
            searchName: this.row.searchName,
            searchCode: this.row.searchCode,
            searchDes: this.row.searchDes,
          }
        })
      },

      queryIsShowButton() {
        queryIsShowButton({
          deviceCode: this.row.deviceCode
        }).then(res => {
          if (res.status == 200) {
            this.btnInfo = res.object
          }
        })
      },

      handlerOpenControl() {
        this.queryControlList()
        this.$refs.controlDialog.dialogVisible = true
      },

      async queryControlList() {
        this.loading = true
        const { object } = await queryControlList({
          deviceCode: this.row.deviceCode
        })
        this.controlDataList = object
        this.loading = false
      },

      editControl(data) {
        this.controlObj = JSON.parse(JSON.stringify(data))
        this.$confirm("确定执行此指令吗, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (this.btnInfo.isSms == "need") {
            this.yzm = ""
            clearInterval(this.timer)
            this.disabled = false
            this.$refs.ycSmsDialog.dialogVisible = true
          } else {
            this.loading = true
            makeDeviceControl({
              deviceCode: this.row.deviceCode,
              parameterCode: data.parameterCode,
              command: data.command,
              commandName: data.commandName
            }).then(res => {
              if (res.status == 200 && (res.message == "指令发送成功" || res.message == "指令发送成功等待核验")) {
                this.$message({
                  type: "success",
                  message: res.message
                })
                this.loading = false
              } else {
                this.$message({
                  type: "error",
                  message: res.message
                })
                this.loading = false
              }
            })
          }
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          })
        })
      },

      //获取短信验证码
      getCode() {
        let that = this
        getSmsCode({
          deviceCode: that.row.deviceCode
        }).then(res => {
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: res.message
            })
            this.yzmCode = res.object
          }
        })
        let s = 59  //倒计时间
        // if (!that.timer) {
        that.second = s
        that.disabled = true
        that.timer = setInterval(() => {
          if (that.second > 0 && this.second <= s) {
            that.second--
          } else {
            that.disabled = false
            clearInterval(that.timer)
            this.timer = null
          }
        }, 1000)
        // }
      },
      selectParamsSave() {
        this.loading = true
        this.addOrUpdateLoading = true
        makeDeviceControlSms({
          deviceCode: this.row.deviceCode,
          parameterCode: this.controlObj.parameterCode,
          command: this.controlObj.command,
          commandName: this.controlObj.commandName,
          yzm: this.yzm,
          yzmCode: this.yzmCode
        }).then(res => {
          if (res.status == 200) {
            if (res.message == "指令发送成功" || res.message == "指令发送成功等待核验") {
              this.$message({
                type: "success",
                message: res.message
              })
              this.$refs.ycSmsDialog.dialogVisible = false
            } else {
              this.$message({
                type: "error",
                message: res.message
              })
            }
          } else {
            this.disabled = false
            clearInterval(this.timer)
            this.timer = null
          }
        })
        this.loading = false
        this.addOrUpdateLoading = false
      },

      // 参数修改
      handlerParams() {
        this.addOrUpdateLoading = false
        queryParamCanUpdateList({
          deviceCode: this.row.deviceCode
        }).then(res => {
          this.paramsTableData = JSON.parse(JSON.stringify(res.object))
          this.paramsTableData2 = JSON.parse(JSON.stringify(res.object))
        })
        this.$refs.paramsDialog.dialogVisible = true
      },
      editParamsSave() {
        this.addOrUpdateLoading = true
        let tempArr = []
        for (let i = 0; i < this.paramsTableData2.length; i++) {
          for (let j = 0; j < this.paramsTableData.length; j++) {
            if ((this.paramsTableData2[i].parameterCode == this.paramsTableData[j].parameterCode) &&
              (this.paramsTableData2[i].parameterValue != this.paramsTableData[j].parameterValue)) {

              let parameterValueName
              if (this.paramsTableData[j].itemList) {
                for (let k = 0; k < this.paramsTableData[j].itemList.length; k++) {
                  if (this.paramsTableData[j].parameterValue == this.paramsTableData[j].itemList[k].key) {
                    parameterValueName = this.paramsTableData[j].itemList[k].value
                  }
                }
              } else {
                parameterValueName = this.paramsTableData[j].parameterValue
              }

              let obj = {
                deviceCode: this.row.deviceCode,
                parameterCode: this.paramsTableData[j].parameterCode,
                parameterName: this.paramsTableData[j].parameterName,
                parameterValue: this.paramsTableData[j].parameterValue,
                parameterValueName
              }
              tempArr.push(obj)
            }
          }
        }

        saveParamCanUpdate({
          listString: JSON.stringify(tempArr)
        }).then(res => {
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: res.message
            })
            this.$refs.paramsDialog.dialogVisible = false
          }
        })
        this.addOrUpdateLoading = false
      },

      // 固件直发
      handlerFirmware() {
        this.addOrUpdateLoading = false
        this.$refs.firmwareDialog.dialogVisible = true
      },

      beforeUpload(file) {
        // const fileFamart = file.name.split(".")[file.name.split(".").length - 1]
        // const suffix = fileFamart === "jpg"
        // const suffix2 = fileFamart === "png"
        // const suffix3 = fileFamart === "jpeg"
        // if (!suffix && !suffix2 && !suffix3) {
        //   this.$message.warning("只能上传图片格式的文件!")
        //   return false
        // }
        // return suffix || suffix2 || suffix3
      },
      //上传图片
      handleLicenseSuccess(id, file) {
        this.newFirmwareModel.fileUrl = file.response.object.url
        this.fileUrl = file.response.object.url
      },
      editFirmwareSave() {
        this.$refs.firmwareFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true

            const { status, message } = await insertInitFirmware({
              ...this.newFirmwareModel,
              deviceCode: this.row.deviceCode
            })
            if (status == 200) {
              this.$message.success(message)
              this.$refs.firmwareDialog.dialogVisible = false
            }

            this.addOrUpdateLoading = false
          }
        })
      }
    }
  }
</script>
<style scoped lang="scss">
  .tab-item {
    width: 25%;
  }

  .tab-buttom {
    position: absolute;
    right: 16px;
  }

  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    /* cursor: no-drop; */
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .drop {
    cursor: no-drop;
  }
</style>
